<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
    <link rel="stylesheet" href="vendors/bootstrap-4.0.0/css/bootstrap.css"/>
    <script src="vendors/jquery/jquery-3.5.1.min.js"></script>
    <script src="vendors/bootstrap-4.0.0/js/bootstrap.bundle.js"></script>
</head>
<body>

<div class="container" style="margin-top: 100px;">
    <button type="button" class="btn-primary" onclick="window.location='/index.html'">返回首页</button>
    <br/>
    <br/>
    <br/>
    <br/>
    <div class="container" style="width: 60%;margin: 0 auto;">
        <form class="form-horizontal" role="form">
            <div class="form-group">
                <label for="username" class="col-sm-2 control-label">用户名</label>
                <div class="col-sm-10">
                    <input required type="text" class="form-control" id="username" placeholder="请输入名字 zhangsan">
                </div>
            </div>
            <div class="form-group">
                <label for="password" class="col-sm-2 control-label">密码</label>
                <div class="col-sm-10">
                    <input required type="text" class="form-control" id="password" placeholder="请输入密码 123">
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="submit" style="width: 100%" class="btn btn-default btn-primary">登录</button>
                </div>
            </div>
        </form>
    </div>
</div>
<script type="text/javascript">
    $(function () {
        $("form").submit(function (e) {
            e.preventDefault();
            const username = $("#username").val();
            const password = $("#password").val();
            $.ajax({
                url: "/login",
                type: "POST",
                data: JSON.stringify({
                    username: username,
                    password: password
                }),
                headers: {
                    'Content-Type': 'application/json'  //application/x-www-form-urlencoded  application/json
                },
                dataType: "json",
                success: function (data, status) {
                    if (!data.success) {
                        alert(data.msg);
                        return;
                    }
                    console.log(data);
                    localStorage.setItem("token", data.data);
                    window.location.href = "/index.html";
                },
                error:function(data,status){
                    alert("登录失败，请检查用户名密码是否正确");
                }
            });
        });
    });
</script>

</body>
</html>